import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {
  getShopList,destorySystem,
  getDictValueList
} from "@/api/system";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { useRouter,useRoute } from 'vue-router';

export function useShop(treeRef: Ref) {
  const route = useRoute();
  const form = reactive({
    shop_name: "",
    status: "",
    status2: "",
    group: +route.query?.group||"",
    standard_code: "",
    own_user: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const groupList = ref([]);
  const userOptions = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });

  const exportExcel = async () => {
    const { data } = await getShopList(toRaw({page:1,export:1,limit:10000}),'get');
    // downloadByUrl(data.url)
    window.open(data.url, '_blank')
  };
  const columns: TableColumnList = [
    {label: "店铺id", prop: "store_id"},
    {label: "投放用户", prop: "admin_user", minWidth: 80},
    {label: "店铺名称", prop: "shop_name", minWidth: 120},
    {label: "店铺域名", prop: "shop_domain", minWidth: 150},
    {label: "服务开始时间", prop: "starts_at",width:130},
    {label: "服务截止时间", prop: "ends_at",width:130},
    {label: "套餐版本ID", prop: "package_type"},
    {label: "时区", prop: "time_zone"},
    {
      label: "Saas状态",
      cellRenderer: scope => (
        scope.row.status==1?'Saas启用':'Saas停用'
      ),
      minWidth: 90
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status2} active-value={1} disabled
          inactive-value={2} active-text="已启用"
          inactive-text="已停用" inline-prompt style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {label: "备注", prop: "remark"},
    {label: "币种", prop: "standard_code",width:70},
    {label: "汇率", prop: "exchange_rate",width:70},
    {label: "创建时间", prop: "created_at", width: 160},
    {label: "操作", fixed: "right", width: 140, slot: "operation"}
  ];


  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(() => {
      row.swith = 1
      getShopList(row,"put").then(res=>{
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message(`已${row.status === 2 ? "停用" : "启用"}${row.name}`, {
          type: "success"
        });
      })
      })
      .catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function handleDelete(row) {
    getShopList(row,"delete").then(res=>chores(row,res,'删除'))
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }
  function destoryData() {
    ElMessageBox.prompt('请输入删除密码', '删除确认', {
      confirmButtonText: 'OK',
      inputPattern: /^[a-zA-Z0-9]{4,16}$/, // 正则验证
      inputErrorMessage: '用户名必须为4-16位字母或数字',
      beforeClose: async(action, instance, done) => {
        if (action === 'confirm') {
          await destorySystem({password: instance.inputValue}, "post").then(res => {
            if (res.code == 1) {
              message(res.message, {type: "error"});
            } else {
              message('删除成功', {type: "success"});
              onSearch()
              done()
            }
          })
        }else{
          done()
        }
      }
    })
  }



  async function onSearch() {
    loading.value = true;
    const searchData = {
      ...toRaw(form),
      page: pagination.currentPage,
      limit: pagination.pageSize
    };
    const { data } = await getShopList(searchData,'get');
    dataList.value = data.data;
    groupList.value = data.group;
    userOptions.value = data.user_options || [];
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.currentPage;


    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function chores(curData,res,title,done) {
    if(res.code===0){
      message(`您${title}了店铺名称为${curData.shop_name}的这条数据`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    }else{
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }
  function openDialog(title = "新增", row?: FormItemProps) {

    row.groupList = groupList.value
    addDialog({
      title: `${title}店铺`,
      props: {
        formInline: JSON.parse(JSON.stringify(row))
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            delete curData.webhooks
            delete curData.domains
            delete curData.groupList
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              getShopList(curData,"post").then(res=>chores(curData,res,title,done))
            } else {
              curData.id = row.id
              // 实际开发先调用修改接口，再进行下面操作
              getShopList(curData,"put").then(res=>chores(curData,res,title,done))
            }
          }
        });
      }
    });
  }

  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }


  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  function handleSave() {
    // 保存函数逻辑，根据项目需要实现
  }

  function handleSelectionChange(selection) {
    // 选择变化处理函数
    console.log('Selection changed:', selection);
  }

  const dictList = ref([])
  onMounted(async () => {
    onSearch();
    const { data } = await getDictValueList(toRaw({limit:10000}));
    dictList.value = data.data;
  });



  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,dictList,groupList,
    userOptions,
    dataList,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    onSearch,
    resetForm,
    openDialog,
    handleSave,
    handleDelete,destoryData,
    handleSelectionChange,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    exportExcel
  };
}
